package bepeb.views;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

public class ExpandAction implements IViewActionDelegate {

	private BEPEBView view;
	private TreePath path;

	public void init(IViewPart view) {
		this.view = (BEPEBView) view;

	}

	public void run(IAction action) {
		if (path != null) {
			Object lastSegment = path.getLastSegment();
			if (lastSegment instanceof IConfigurationElement) {
				view.getViewer().expandToLevel(path, AbstractTreeViewer.ALL_LEVELS);
			} else {
				int segmentCount = path.getSegmentCount();
				view.getViewer().expandToLevel(path, (segmentCount > 6 ? 1 : 3));
			}
		}
	}

	public void selectionChanged(IAction action, ISelection selection) {
		path = null;
		action.setEnabled(false);
		if (selection instanceof ITreeSelection) {
			ITreeSelection treeSelection = (ITreeSelection) selection;
			TreePath[] paths = treeSelection.getPaths();
			if (paths.length > 0) {
				path = paths[0];
				action.setEnabled(true);
			}
		}
	}

}
